package com.ye.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ye.dao.AppInfoDao;
import com.ye.dto.AppInfoDto;
import com.ye.entity.AppInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class AppInfoService {
    @Autowired
    AppInfoDao appInfoDao;
    public PageInfo<AppInfo> getPage(AppInfoDto appInfoDto, Integer pageNum) {
        AppInfo appInfo = new AppInfo();
        BeanUtils.copyProperties(appInfoDto,appInfo);
        PageHelper.startPage(pageNum,5);
        List<AppInfo> list =appInfoDao.queryAllBy(appInfo);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public void saveOrUpdate(AppInfo appInfo) {
        if (appInfo.getId()==null) {
            appInfoDao.insert(appInfo);
        }else {
            AppInfo a = appInfoDao.queryById(appInfo.getId());
            new File(a.getLogopicpath()).delete();
            appInfoDao.update(appInfo);
        }
    }

    public AppInfo getOne(Long id) {
        AppInfo appInfo = appInfoDao.queryById(id);
        return appInfo;
    }

    public void del(Long id) {
        appInfoDao.deleteById(id);
    }

    public void sale(Long id) {
        AppInfo appInfo = appInfoDao.queryById(id);
        if (appInfo.getStatus()==5L) {
            appInfo.setStatus(4L);
            appInfo.setOnsaledate(new Date());
        }else if (appInfo.getStatus()==4L) {
            appInfo.setStatus(5L);
            appInfo.setOffsaledate(new Date());
        }
        appInfoDao.update(appInfo);
    }

    public Boolean validate(AppInfo appInfo) {
        AppInfo appInfo1 = appInfoDao.queryById(appInfo.getId());
        if (appInfo.getId()!=null){
            if (appInfo.getApkname().equals(appInfo1.getApkname())){
                return true;
            }
        }
        Integer count = appInfoDao.validate(appInfo.getApkname());
        if (count>0) {
            return false;
        }
        return true;
    }
}
